package com.atguigu.daijia.dispatch.xxl.job;

import com.atguigu.daijia.dispatch.mapper.XxlJobLogMapper;
import com.atguigu.daijia.dispatch.service.NewOrderService;
import com.atguigu.daijia.model.entity.dispatch.XxlJobLog;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class JobHandler {
    @Autowired
    private XxlJobLogMapper xxlJobLogMapper;
    @Autowired
    private NewOrderService newOrderService;
    @XxlJob("newOrderTaskHandler")
    public void newOrderTaskHandler(){
        log.info("新订单调度任务:{}", XxlJobHelper.getJobId());
        //记录定时任务相关的日志信息
        //封装日志对象
        XxlJobLog xxlJobLog = new XxlJobLog();
        xxlJobLog.setJobId(XxlJobHelper.getJobId());
        long startTime = System.currentTimeMillis();
        try {
            //执行任务
            newOrderService.exeNewOrderTask(XxlJobHelper.getJobId());
            xxlJobLog.setStatus(1);//成功
        }catch (Exception e) {
            log.error("新订单调度任务执行失败：{}",e.getMessage());
            xxlJobLog.setStatus(0);//失败
            xxlJobLog.setError(ExceptionUtils.getStackTrace(e));
            e.printStackTrace();
        }finally {
            //耗时
            int times = (int) (System.currentTimeMillis() - startTime);
            xxlJobLog.setTimes(times);
            xxlJobLogMapper.insert(xxlJobLog);

        }
    }
}
